package cn.ac.iscas.action.paper;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.type.CalendarType;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.ac.iscas.bean.PageView;
import cn.ac.iscas.bean.paper.ConferenceType;
import cn.ac.iscas.bean.paper.ConfererncePaper;
import cn.ac.iscas.bean.paper.JournalLevel;
import cn.ac.iscas.bean.paper.JournalPaper;
import cn.ac.iscas.bean.paper.Paper;
import cn.ac.iscas.bean.paper.PaperDocument;
import cn.ac.iscas.bean.project.ProjectDocument;
import cn.ac.iscas.service.paper.IConferencePaperService;
import cn.ac.iscas.service.paper.IJournalServive;
import cn.ac.iscas.service.paper.IPaperDocumentService;
import cn.ac.iscas.service.paper.IPaperService;

@Controller @Scope("prototype")
public class PaperQuery {
	private QueryCondition queryCondition;
	private int page;
	PaperDocument document;
	private Paper paper;
	
	@Resource private IPaperService paperService;
	@Resource private IJournalServive journalPaperService;
	@Resource private IConferencePaperService conferencePaperService;
	@Resource private IPaperDocumentService paperDocumentService;
	private String paperType;//论文类型
	public String detailQuery()
	{
		paper = paperService.get(Paper.class, paper.getId());
		if(paper instanceof ConfererncePaper)
		{
			ConfererncePaper confererncePaper = (ConfererncePaper)paper;
			ActionContext.getContext().put("conferencePaper",confererncePaper);
			return "conferencePaperDetails";
		}
		else 
		{
			JournalPaper journal = (JournalPaper)paper;
			ActionContext.getContext().put("journal",journal);
			return "journalDetail";
		}
	}
	public String edit()
	{
		paper = paperService.get(Paper.class, paper.getId());
		if(paper instanceof ConfererncePaper)
		{
			ConfererncePaper confererncePaper = (ConfererncePaper)paper;
			ActionContext.getContext().put("conferencePaper",confererncePaper);
			return "conferencePaperEdit";
		}
		else 
		{
			JournalPaper journalPaper = (JournalPaper)paper;
			ActionContext.getContext().put("journalPaper",journalPaper);
			return "journalEdit";
		}
	}
	public String list()
	{
		page = (0==page)?1:page;
		PageView<Paper> pageView = new PageView<Paper>(7, page);
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("publicationYear", "desc");
		pageView.setQueryResult(paperService.getScrollData(Paper.class,pageView.getFirstResult(),pageView.getMaxresult(), orderby));
		ActionContext.getContext().put("pageView", pageView);
		return "success";
	}
	public String query()
	{
		if(page<=0)page=1;
	    StringBuffer jpql = new StringBuffer("");
	    StringBuffer sql = new StringBuffer("");
	    boolean useSql = false;
		List<Object> params = new ArrayList<Object>();
		
		if(queryCondition.getConferencePaper()!=null && !"".equals(queryCondition.getConferencePaper())
				&& queryCondition.getJournal()!=null && !"".equals(queryCondition.getJournal())){
			useSql = true;
		}
		
		if(queryCondition.getPaperTittle()!=null && !"".equals(queryCondition.getPaperTittle())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.paperTittle like ?");
			params.add("%"+ queryCondition.getPaperTittle()+ "%");
			if(useSql == true)				
				sql.append(" AND paperTittle like '%"+queryCondition.getPaperTittle()+"%'");
			
		}
		if(queryCondition.getKeyWord()!=null && !"".equals(queryCondition.getKeyWord())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.keyWord like ?");
			params.add("%"+ queryCondition.getKeyWord()+ "%");
			if(useSql = true)			
				sql.append(" AND keyWord like '%"+queryCondition.getKeyWord()+"%'");
			
		}
		if(queryCondition.getPublicationYear()!=null && !"".equals(queryCondition.getPublicationYear())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.publicationYear = ?");
			params.add(queryCondition.getPublicationYear());
			if(useSql = true)			
				sql.append(" AND publicationYear='"+queryCondition.getPublicationYear()+"'");
			
	
			
			//	int year = Integer.parseInt(queryCondition.getPublicationYear());
		//	System.out.println(year);
		//	Calendar beginDate = Calendar.getInstance();
		//	beginDate.set(year, 0, 1);
		//	int nextYear = year+1;
		//	System.out.println(nextYear);
		//	Calendar endDate = Calendar.getInstance();
		//	endDate.set(nextYear, 0, 1);
		//  System.out.println(beginDate);
	//	    System.out.println(endDate);
		//	if(params.size()>0) jpql.append(" and ");
		//	System.out.println(queryCondition.getPublicationYear()+"getPublicationYear"+"\n");
		//	jpql.append(" o.publicationYear >= ?");
		//	params.add(beginDate);
		//	jpql.append(" and o.publicationYear < ?");
		//	params.add(endDate);
			
		}
		if(queryCondition.getAuthor()!=null && !"".equals(queryCondition.getAuthor())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" ((o.firstAuthor like ? ");
			params.add("%"+queryCondition.getAuthor()+"%");
			jpql.append("or o.secondAuthor like ? ");
			params.add("%"+queryCondition.getAuthor()+"%");
			jpql.append("or o.thirdAuthor like ? ");
			params.add("%"+queryCondition.getAuthor()+"%");
			jpql.append("or o.fourthAuthor like ? ");
			params.add("%"+queryCondition.getAuthor()+"%");
			jpql.append("or o.fifthAuthor like ? ");
			params.add("%"+queryCondition.getAuthor()+"%");
			jpql.append("or o.sixthAuthor like ? )) ");
			params.add("%"+queryCondition.getAuthor()+"%");
			if(useSql = true)
			{				
				sql.append(" AND (paper.firstAuthor like '%"+queryCondition.getAuthor()+"%'");
				sql.append(" OR secondAuthor like '%"+queryCondition.getAuthor()+"%'");
				sql.append(" OR thirdAuthor like '%"+queryCondition.getAuthor()+"%'");
				sql.append(" OR fourthAuthor like '%"+queryCondition.getAuthor()+"%'");
				sql.append(" OR fifthAuthor like '%"+queryCondition.getAuthor()+"%'");
				sql.append(" OR sixthAuthor like '%"+queryCondition.getAuthor()+"%')");
				
			}
			
		}
		if(queryCondition.getFirstAuthor()!=null && !"".equals(queryCondition.getFirstAuthor())){
			System.out.println(queryCondition.getFirstAuthor());
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.firstAuthor like ?");
			params.add("%"+queryCondition.getFirstAuthor()+"%");
			if(useSql = true)		
				sql.append(" AND firstAuthor like '%"+queryCondition.getAuthor()+"%'");
		
		}
		
		if(queryCondition.getJournal()!=null && !"".equals(queryCondition.getJournal()) && 
				queryCondition.getConferencePaper() == null && !"".equals(queryCondition.getJournal()))
		{
			if("一级期刊".equals(queryCondition.getJournal()))
			{
				if(params.size()>0) jpql.append(" and ");
				jpql.append(" o.journalLevel like ?");
				params.add(JournalLevel.一级);
			}
			else if("核心期刊".equals(queryCondition.getJournal()))
			{
				if(params.size()>0) jpql.append(" and ");
				jpql.append(" o.journalLevel like ?");
				params.add(JournalLevel.核心);
			}
			else if("国际期刊".equals(queryCondition.getJournal()))
			{
				if(params.size()>0) jpql.append(" and ");
				jpql.append(" o.journalLevel like ?");
				params.add(JournalLevel.国际);
			}
			PageView<JournalPaper> pageView=new PageView<JournalPaper>(7,page);
			LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
			orderby.put("publicationYear", "desc"); 
			pageView.setQueryResult(journalPaperService.getScrollData(JournalPaper.class,pageView.getFirstResult(), 
					pageView.getMaxresult(), jpql.toString(), params.toArray(), orderby));
			ActionContext.getContext().put("pageView", pageView);
		}
		else if(queryCondition.getConferencePaper()!=null && !"".equals(queryCondition.getConferencePaper()) 
				&& queryCondition.getJournal() == null && !"".equals(queryCondition.getJournal()))
		{
			if("国内会议".equals(queryCondition.getConferencePaper()))
			{
				if(params.size()>0) jpql.append(" and ");
				jpql.append(" o.conferenceType like ?");
				params.add(ConferenceType.国内);
			}
			else if("国际会议".equals(queryCondition.getConferencePaper()))
			{
				if(params.size()>0) jpql.append(" and ");
				jpql.append(" o.conferenceType like ?");
				params.add(ConferenceType.国际);
			}
			PageView<ConfererncePaper> pageView=new PageView<ConfererncePaper>(7,page);
			LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
			orderby.put("publicationYear", "desc"); 
			pageView.setQueryResult(conferencePaperService.getScrollData(ConfererncePaper.class,pageView.getFirstResult(), 
					pageView.getMaxresult(), jpql.toString(), params.toArray(), orderby));
			ActionContext.getContext().put("pageView", pageView);
		}
		else if(queryCondition.getConferencePaper()!=null && !"".equals(queryCondition.getConferencePaper())
				&& queryCondition.getJournal()!=null && !"".equals(queryCondition.getJournal()))
		{
			StringBuffer sqlJournal = new StringBuffer(sql);
			if("一级期刊".equals(queryCondition.getJournal()))			
				sqlJournal.append(" AND journalLevel = '"+JournalLevel.一级+"'");
		
			else if("核心期刊".equals(queryCondition.getJournal()))			
				sqlJournal.append(" AND journalLevel = '"+JournalLevel.核心+"'");
			
			else if("国际期刊".equals(queryCondition.getJournal()))			
				sqlJournal.append(" AND journalLevel = '"+JournalLevel.国际+"'");
		
			StringBuffer sqlConference = new StringBuffer(sql);
			if("国内会议".equals(queryCondition.getConferencePaper()))
			
				sqlConference.append(" AND conferenceType = '"+ConferenceType.国内+"'");
			
			else if("国际会议".equals(queryCondition.getConferencePaper()))			
				sqlConference.append(" AND conferenceType = '"+ConferenceType.国际+"'");
			System.out.println(sqlJournal);
			System.out.println(sqlConference);
			String sqlResultPre = "(SELECT paper.* FROM paper,journalpaper WHERE id=journalpaper.paper_id" + sqlJournal
				+") UNION (SELECT paper.* FROM paper,confererencepaper WHERE id=confererencepaper.paper_id " + sqlConference +")";
			String sqlResult = sqlResultPre +";";
			String resultCount = "SELECT COUNT(*) FROM ("+sqlResultPre+") as result;";
			System.out.println(sqlResult);
			System.out.println(resultCount);
			PageView<Paper> pageView=new PageView<Paper>(7,page);
			
			pageView.setQueryResult(paperService.getScrollData(sqlResult,resultCount,pageView.getFirstResult(), 
					pageView.getMaxresult()));
			ActionContext.getContext().put("pageView", pageView);
		}
		else{
			PageView<Paper> pageView=new PageView<Paper>(7,page);
			LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
			orderby.put("publicationYear", "desc"); 
			pageView.setQueryResult(paperService.getScrollData(Paper.class,pageView.getFirstResult(), 
					pageView.getMaxresult(), jpql.toString(), params.toArray(), orderby));
			ActionContext.getContext().put("pageView", pageView);
		}
		return "success";
	}
	/**
	 * 
	 *删除论文Ajax
	 * */
	public String deleteDocument() throws IOException
	{
		System.out.println(document.getId());
		document = paperDocumentService.get(PaperDocument.class, document.getId());
		paperDocumentService.delete(document);
		ActionContext ctx = ActionContext.getContext();     
	    HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
	    response.setContentType("text/html;charset=utf-8");
	    PrintWriter out=response.getWriter();
	    response.setContentType("text/html;charset=utf-8");
	    out.println("成功删除");
		return null;
	}
	public String delete() throws IOException
	{
		paper = paperService.get(Paper.class,paper.getId());
		paperService.delete(paper);
		ActionContext ctx = ActionContext.getContext();     
	    HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
	    response.setContentType("text/html;charset=utf-8");
	    PrintWriter out=response.getWriter();
	    response.setContentType("text/html;charset=utf-8");
	    out.println("成功删除");
		return null;
	}
	public void setPaper(Paper paper) {
		this.paper = paper;
	}
	public Paper getPaper() {
		return paper;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getPage() {
		return page;
	}
	public void setPaperService(IPaperService paperService) {
		this.paperService = paperService;
	}
	public IPaperService getPaperService() {
		return paperService;
	}
	public void setPaperType(String paperType) {
		this.paperType = paperType;
	}
	public String getPaperType() {
		return paperType;
	}
	public void setQueryCondition(QueryCondition queryCondition) {
		this.queryCondition = queryCondition;
	}
	public QueryCondition getQueryCondition() {
		return queryCondition;
	}
	public IJournalServive getJournalPaperService() {
		return journalPaperService;
	}
	public void setJournalPaperService(IJournalServive journalPaperService) {
		this.journalPaperService = journalPaperService;
	}
	public IConferencePaperService getConferencePaperService() {
		return conferencePaperService;
	}
	public void setConferencePaperService(
			IConferencePaperService conferencePaperService) {
		this.conferencePaperService = conferencePaperService;
	}
	public PaperDocument getDocument() {
		return document;
	}
	public void setDocument(PaperDocument document) {
		this.document = document;
	}
	public IPaperDocumentService getPaperDocumentService() {
		return paperDocumentService;
	}
	public void setPaperDocumentService(IPaperDocumentService paperDocumentService) {
		this.paperDocumentService = paperDocumentService;
	}
}
